package com.bosssoft.hr.jobmonitor.util;

import com.bosssoft.hr.jobmonitor.core.Timer.CheckFileTaskTool;
import com.bosssoft.hr.jobmonitor.core.Timer.RemindMailRunnable;
import com.bosssoft.hr.jobmonitor.core.auth.AuthInterceptor;
import com.bosssoft.hr.jobmonitor.core.file.FileTool;
import com.bosssoft.hr.jobmonitor.core.mail.EmailTool;
import com.bosssoft.hr.jobmonitor.core.Timer.CheckFileTaskTool;
import com.bosssoft.hr.jobmonitor.entity.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;


import java.util.Date;
import java.util.concurrent.ScheduledFuture;

/***
 * @Author lys(cherish)
 * @Description 定时操作工具
 * @Date  2019/2/26
 **/
@Component
public class SchedulerUtil {

    private static final Logger logger= LoggerFactory.getLogger(SchedulerUtil.class);

    //线程任务执行的”结果“
    private ScheduledFuture<?> future;

    //线程池任务定时器注入
    @Autowired
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;

    //检查文件任务工具注入
    @Autowired
    private CheckFileTaskTool checkFileTaskTool;

    //文件处理工具注入
    @Autowired
    private FileTool readFileTool;

    //邮件处理工具
    @Autowired
    private EmailTool emailTool;

    /***
     * @Author lys(cherish)
     * @Description 启动定时，定时为单次具体时间日期执行
     * @Date  2019/2/26
     * @Param [task, sendTime] 任务、邮件发送的时间
     * @return void
     **/
    public void startCron(Task task,Date sendTime) {
//        Cron expression must consist of 6 fields (found 7 in "00 03 21 23 03 ? 2019")
        String cron = DateUtil.getCron(sendTime).split("[?]")[0] + "?";
        future = threadPoolTaskScheduler.schedule(new RemindMailRunnable(task,checkFileTaskTool,emailTool,readFileTool), new CronTrigger(cron));
    }

    /***
     * @Author lys(cherish)
     * @Description 停止定时，暂未使用
     * @Date  2019/2/26
     * @Param []
     * @return void
     **/
    public void stopCron() {
        if (future != null) {
            future.cancel(true);
        }
        logger.info(LoggerUtil.fmtLog("停止定时任务"));
    }

    /***
     * @Author lys(cherish)
     * @Description 修改定时，暂未使用
     * @Date  2019/2/26
     * @Param [task]
     * @return void
     **/
    public void startCron10(Task task) {
        // 先停止，在开启.
        stopCron();
        future = threadPoolTaskScheduler.schedule(new RemindMailRunnable(task,checkFileTaskTool,emailTool,readFileTool), new CronTrigger("*/10 * * * * *"));
        logger.info(LoggerUtil.fmtLog("修改定时"));
    }

}
